<template>
	<view class="register-container">
		<view class="form-card">
			<text class="title">{{ getTitleByType(form.userType) }}</text>

			<!-- 姓名 -->
			<view class="input-item">
				<input class="input" v-model="form.nickname" placeholder="请输入姓名" />
			</view>

			<!-- 手机号 -->
			<view class="input-item">
				<input class="input" v-model="form.mobile" placeholder="请输入手机号" type="number" />
			</view>

			<!-- 获取验证码 -->
			<view class="input-item">
				<input class="input" v-model="form.smsCode" placeholder="请输入验证码" />
				<button class="code-btn" @click="getVerificationCode" :disabled="isSendingCode">
					{{ isSendingCode ? `${countdown}s` : '获取验证码' }}
				</button>
			</view>

			<!-- 密码 -->
			<view class="input-item">
				<input class="input" v-model="form.password" placeholder="请输入密码" type="password" />
			</view>

			<!-- 确认密码 -->
			<view class="input-item">
				<input class="input" v-model="form.checkPassword" placeholder="确认密码" type="password" />
			</view>

			<!-- 身份证号 -->
			<view class="input-item">
				<input class="input" v-model="form.idcard" placeholder="请输入身份证号" />
			</view>

			<!-- 上传身份证正面 -->
			<text class="label">上传身份证（正面）</text>
			<uni-file-picker limit="1" file-mediatype="image" v-model="form.idcardPicFront" mode="grid"
				:imageStyles="imageStyle" @select="(e) => handleImageSelect(e, 'idcardPicFront')" />

			<!-- 上传身份证反面 -->
			<text class="label">上传身份证（反面）</text>
			<uni-file-picker limit="1" file-mediatype="image" v-model="form.idcardPicBack" mode="grid"
				:imageStyles="imageStyle" @select="(e) => handleImageSelect(e, 'idcardPicBack')" />

			<!-- 上传资格证 -->
			<view v-if="form.userType == '1'">
			<text class="label">上传资格证照片</text>
			<uni-file-picker limit="9" file-mediatype="image" v-model="form.certPic" mode="grid"
				:imageStyles="imageStyle" @select="(e) => handleImageSelect(e, 'certPic')" />
			</view>
			<!-- 运维区域选择 -->
			<text class="label">运维区域</text>
			  <view class="area-list">
			    <view v-for="(item, index) in form.areas" :key="index" class="area-item">
			      <view class="area-picker-container">
			        <uni-data-picker 
			          ref="areaPicker" 
			          placeholder="请选择运维区域" 
			          v-model="form.areas[index]"
			          :localdata="areaData" 
			          :map="{ text: 'label', value: 'value' }" 
			          :level="4" 
			          popup-title="选择区域"
			          @change="onAreaChange(index, $event)" 
			          class="area-picker"
			        />
<!-- 			        <view class="icon-btn remove-btn" @click="removeArea(index)">
			          <uni-icons type="minus" size="20" color="#ff4d4f"></uni-icons>
			        </view> -->
			      </view>
			    </view>
			    
			    <!-- 添加按钮 -->
<!-- 			    <view class="add-area-btn" @click="addArea">
			      <uni-icons type="plus" size="20" color="#1890ff"></uni-icons>
			      <text>添加区域</text>
			    </view> -->
			  </view>

			<!-- 提交按钮 -->
			<button class="submit-btn" @click="submitForm">提交注册</button>

			<!-- 返回登录按钮 -->
			<button class="back-btn" @click="backToLogin">返回登录</button>
		</view>
	</view>
</template>

<script>
	import * as UserApi from "@/api/oper/user/user.js";
	import * as UploadApi from "@/api/infra/upload.js";
	import * as AreaApi from "@/api/system/area.js";

	export default {
		data() {
			return {
				form: {
					userType: '',
					nickname: '',
					mobile: '',
					smsCode: '',
					password: '',
					checkPassword: '',
					idcard: '',
					idcardPicFront: [],
					idcardPicBack: [],
					certPic: [],
					areas: [], // 运维区域数组
					status: 0,
				},
				areaData: [], // 前三级区域数据
				townData: [], // 第四级数据
				townDataMap: {}, // 每个区对应的镇列表
				currentEditingIndex: null, // 记录当前正在编辑的区域索引
				imageStyle: {
					width: 80,
					height: 80,
					border: {
						radius: '8px'
					}
				},
				isSendingCode: false, // 是否正在发送验证码
				countdown: 60, // 验证码倒计时
				countdownTimer: null // 用于存储倒计时定时器
			};
		},
		async onLoad(options) {
			const type = options.type;
			console.log('接收到的type是：', type)
			if (type === '0') {
				this.form.userType = '0';
			} else if (type === '1') {
				this.form.userType = '1';
			}
			await this.loadAreaData();	
			this.addArea();
		},
		methods: {
			getTitleByType(type) {
			  switch (type) {
				case '0':
				  return '注册共享电工'
				case '1':
				  return '注册持证电工'
				default:
				  return '注册'
			  }
			},
			// 获取验证码方法
			getVerificationCode() {
				if (!this.form.mobile) {
					return uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
				}

				if (this.isSendingCode) return; // 防止多次点击

				this.isSendingCode = true;
				this.startCountdown();

				//发送验证码
				UserApi.genCheckCode(this.form.mobile).then(response => {
					if (response.code === 0) {
						uni.showToast({
							title: '验证码已发送',
							icon: 'success'
						});

					} else {
						//  uni.showToast({ title: '验证码发送失败:'+data.msg, icon: 'fail' });
					}
				})
				// 模拟发送验证码
				console.log(`发送验证码到手机号: ${this.form.mobile}`);
			},

			// 启动验证码倒计时
			startCountdown() {
				this.countdownTimer = setInterval(() => {
					if (this.countdown > 0) {
						this.countdown--;
					} else {
						this.isSendingCode = false;
						clearInterval(this.countdownTimer);
						this.countdown = 60;
					}
				}, 1000);
			},

			handleImageSelect(e, type) {
				console.log(type);
				const file = e.tempFiles[0]
				if (!file) return
				UploadApi.uploadImage(file.path, type, (url) => {
					// 上传成功后写入对应字段
					this.form[type] = [{
						url
					}]
				})
			},
			async loadAreaData() {
				try {
					const res = await AreaApi.getAreaList()
					// 确保返回的数据是 Array 类型
					if (res && Array.isArray(res.data)) {
						this.areaData = this.formatAreaTree(res.data)
					} else {
						console.error('地区数据格式错误', res)
					}
				} catch (err) {
					console.error('获取地区失败', err)
				}
			},
			formatAreaTree(data) {
				return data.map(item => ({
					label: item.name,
					value: item.id,
					children: item.children ? this.formatAreaTree(item.children) : []
				}))
			},
			// 区域选择变化时的处理
			async onAreaChange(index, e) {
				const selectedNodes = e.detail.value;
				const selectedValues = selectedNodes.map(node => node.value);

				this.$set(this.form.areas, index, selectedValues);
				this.currentEditingIndex = index;

				// 如果选择了三级区域，则加载第四级数据
				if (selectedValues.length === 3) {
					const districtId = selectedValues[2];
					await this.loadTownData(districtId, index);

					// 数据加载完成后，重新打开选择器
					this.$nextTick(() => {
						if (this.$refs.areaPicker && this.$refs.areaPicker[index]) {
							this.$refs.areaPicker[index].show(); // 重新打开选择器
						}
					});
				}
			},

			// 加载镇级数据
			async loadTownData(districtId, index) {
				// 如果缓存中已有数据，则直接使用
				if (this.townDataMap[districtId]) {
					this.updateTownData(districtId, index);
					return;
				}

				try {
					const res = await AreaApi.getTownList(districtId);
					if (res && res.data && Array.isArray(res.data.list)) {
						// 格式化镇级数据
						const towns = res.data.list.map(town => ({
							label: town.name,
							value: town.id
						}));

						// 缓存数据
						this.$set(this.townDataMap, districtId, towns);

						// 更新区域树数据
						this.updateTownData(districtId, index);
					}
				} catch (err) {
					console.error('获取镇级数据失败', err);
				}
			},

			// 更新区域树数据，添加镇级选项
			updateTownData(districtId, index) {
				// 深拷贝区域树数据
				const areaTreeData = JSON.parse(JSON.stringify(this.areaData));

				// 递归查找并添加镇级数据
				const addTownsToTree = (nodes) => {
					for (const node of nodes) {
						if (node.value === districtId) {
							// 找到对应的区级节点，添加镇级数据
							node.children = this.townDataMap[districtId];
							return;
						}
						if (node.children && node.children.length > 0) {
							addTownsToTree(node.children);
						}
					}
				};

				addTownsToTree(areaTreeData);

				// 更新区域树数据
				this.areaData = areaTreeData;

				// 强制更新选择器
				this.$forceUpdate();
			},

			addArea() {
				this.form.areas.push([]); // 每项是一个数组，保存四级区域值
			},
			removeArea(index) {
				this.form.areas.splice(index, 1);
			},
			

			// 提交注册表单
			submitForm() {
				console.log(this.form);
				
				// 必填字段验证
				if (!this.form.nickname || !this.form.mobile || !this.form.smsCode || 
				    !this.form.password || !this.form.checkPassword) {
				  return uni.showToast({
				    title: '请填写完整信息',
				    icon: 'none'
				  });
				}
				
				// 密码一致性验证
				if (this.form.password !== this.form.checkPassword) {
				  return uni.showToast({
				    title: '密码与确认密码不一致',
				    icon: 'none'
				  });
				}
				
				// 证件照片验证
				if (this.form.idcardPicFront.length === 0 || 
				    this.form.idcardPicBack.length === 0 || 
				    (this.form.userType == 1 && this.form.certPic.length === 0)) {
				  return uni.showToast({
				    title: '请上传所有证件照片',
				    icon: 'none'
				  });
				}
				
				// 手机号格式验证
				if (!/^1[3-9]\d{9}$/.test(this.form.mobile)) {
				  return uni.showToast({
				    title: '请输入正确的11位手机号码',
				    icon: 'none'
				  });
				}
				
				// 身份证格式验证（支持18位和15位）
				if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(this.form.idcard)) {
				  return uni.showToast({
				    title: '请输入正确的身份证号码',
				    icon: 'none'
				  });
				}
				
				const areaList = this.form.areas
				  .filter(area => area && area[0] !== undefined && area[0] !== null && area[0] !== '')
				  .map(area => {
				    const [provinceId, cityId, areaId, townId] = area;
				    return {
				      provinceId,
				      cityId,
				      areaId,
				      townId
				    };
				});
				
				if(areaList.length == 0){
					return uni.showToast({
					  title: '至少包含一个运维区域',
					  icon: 'none'
					});
				}
				if(areaList.length >1){
					return uni.showToast({
					  title: '当前限制只能选择一个运维区域',
					  icon: 'none'
					});
				}

				// 模拟提交，可以接入API
				console.log('注册表单：', this.form);
				//图片格式需要进行转换 uni-file-picker 文件结构问题导致
				const formData = {
					...this.form,
					idcardPicFront: this.form.idcardPicFront?.map(item => item.url),
					idcardPicBack: this.form.idcardPicBack?.map(item => item.url),
					certPic: this.form.certPic?.map(item => item.url)
				};
				

				
				formData.areaList = areaList;

				UserApi.createUser(formData).then(response => {
					if (response.code === 0) {
						uni.showToast({
							title: '注册成功',
							icon: 'success',
							duration: 1500
						});

						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/registerSuccess'
							});
						}, 1500);
					} else {
						uni.showToast({
							title: '注册失败:' + response.msg,
							icon: 'fail'
						});
					}
				})
			},

			// 返回登录页面
			backToLogin() {
				uni.navigateTo({
					url: '/pages/login'
				});
			}
		},
		beforeDestroy() {
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer); // 清除定时器
			}
		}
	};
</script>

<style lang="scss" scoped>
	.register-container {
		display: flex;
		justify-content: center;
		padding: 40rpx;
		background-color: #f7f7f7;
	}

	.form-card {
		width: 100%;
		max-width: 700rpx;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		padding: 40rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.input-item {
		display: flex;
		align-items: center;
		margin-top: 40rpx;
		margin-bottom: 30rpx;
		background-color: #f6f6f6;
		border-radius: 25rpx;
		height: 60rpx;
		padding-left: 20rpx;
	}

	.input {
		flex: 1; /* 让输入框占据剩余空间 */
		width: 100%;
		height: 100%;
		background-color: transparent;
		border: none;
		font-size: 28rpx;
		line-height: 60rpx;
		margin-right: 10rpx; /* 给输入框和按钮之间添加间距 */
	}

	.input:focus {
		outline: none;
		border-bottom: 2px solid #007aff;
	}

	.code-btn {
	  background-color: #07C160; /* 更清新的绿色 */
	  color: white;
	  border-radius: 8rpx;
	  font-size: 28rpx; /* 增大字号 */
	  height: 60rpx; /* 增加高度 */
	  min-width: 200rpx; /* 使用固定宽度替代百分比 */
	  padding: 0 20rpx; /* 添加内边距 */
	  margin-left: 20rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  border: none; /* 移除默认边框 */
	  box-sizing: border-box;
	  line-height: 1; /* 固定行高 */
	  white-space: nowrap; /* 防止文字换行 */
	  transition: all 0.3s; /* 添加过渡效果 */
	}

	/* 禁用状态样式 */
	.code-btn[disabled] {
	  background-color: #A0E57C;
	  opacity: 0.7;
	}

	/* 点击效果 */
	.code-btn:active {
	  transform: scale(0.98);
	  opacity: 0.9;
	}

	.label {
		font-size: 26rpx;
		margin-top: 20rpx;
		margin-bottom: 10rpx;
		display: block;
		color: #333;
	}

	.submit-btn {
		background-color: #2ecc71;
		color: white;
		border-radius: 10rpx;
		margin-top: 30rpx;
		height: 70rpx;
		font-size: 30rpx;
	}

	.back-btn {
		background-color: #f0f0f0;
		color: #666;
		border-radius: 10rpx;
		margin-top: 20rpx;
		height: 70rpx;
		font-size: 30rpx;
	}

	.submit-btn,
	.back-btn {
		width: 100%;
	}
	
	.area-list {
	  width: 100%;
	  
	  .area-item {
	    margin-bottom: 16rpx;
	    
	    .area-picker-container {
	      display: flex;
	      align-items: center;
	      
	      .area-picker {
	        flex: 1;
	        margin-right: 16rpx;
	      }
	      
	      .icon-btn {
	        width: 60rpx;
	        height: 60rpx;
	        display: flex;
	        align-items: center;
	        justify-content: center;
	        background-color: #f5f5f5;
	        border-radius: 8rpx;
	        
	        &.remove-btn {
	          background-color: #fff2f0;
	        }
	      }
	    }
	  }
	  
	  .add-area-btn {
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    padding: 16rpx;
	    color: #1890ff;
	    font-size: 28rpx;
	    background-color: #f0f9ff;
	    border-radius: 8rpx;
	    
	    .uni-icons {
	      margin-right: 8rpx;
	    }
	  }
	}
</style>